import { FC, SetStateAction, useEffect, useRef, useState } from 'react'
import './style.less'
import { HsAdminInput, HsAdminPage, HsAdminSelect, HsAdminSpin, HsAdminTable } from '@hs-admin/base-components'
import { Button, Flex, Menu, Tabs } from 'antd'
import {
  getCompanyEventsCompanyList,
  getCompanyEventsList,
  getCompanyEventsStatistics,
  getMonitorsRollCallList,
  getMonitorsTrackList
} from '@/api/monitors'
import classNames from 'classnames'
import { useAddTrack, useAddCompany } from './add'
import useCompanyManage from './CompanyManage'
import dayjs from 'dayjs'
import { useDebounceFn } from 'ahooks'
import InfiniteScroll from 'react-infinite-scroll-component'
import { useSearchParams } from 'react-router-dom'
import { openCompanyDetail } from 'hs-react-company'
import { DetailModal } from '@hs-server/components'

let PAGE_SIZE = 30
const Monitors: FC = () => {
  const [searchParams] = useSearchParams()
  const [loading, setloading] = useState(true)
  const [OpenKeys, setOpenKeys] = useState<string[]>([])
  const [selectedKeys, setselectedKeys] = useState<string[]>([])
  const [leftTabItems, setleftTabItems] = useState<any[]>([])
  const [selectedTrackItem, setselectedTrackItem] = useState<any>({})
  const [rightHeaderTabs, setrightHeaderTabs] = useState<any[]>([])
  const [rightHeaderTabIndex, setrightHeaderTabIndex] = useState(0)
  const [filterTabs, setfilterTabs] = useState<any[]>([])
  const [occur_date__before, setoccur_date__before] = useState<string | null>(null)
  const [keywords, setkeywords] = useState(null)
  const [event_grade, setevent_grade] = useState<string | null>(null)
  const [event_sub_type, setevent_sub_type] = useState<string | null>(null)
  const [event_segment, setevent_segment] = useState<string | null>(null)
  const [tableActiveKey, settableActiveKey] = useState('1')
  const DetailModalRef = useRef<any>(null)
  const columns = [
    {
      title: '时间',
      dataIndex: 'occur_date',
      width: 100,
      type: 'date'
    },
    {
      title: '标题',
      dataIndex: 'event_title',
      ellipsis: true,
      width: 510,
      render: (text: string, record: any) => (
        <Button
          type="link"
          onClick={() => {
            const obj = {
              id: record.source_id,
              sourceTable: record.source_table,
              eventSubType: record.event_sub_type,
              eventSegment: record.event_segment === '药品申请上市' ? '新药管线' : record.event_segment,
              companyName: record.company_name,
              company_name: record.company_name,
              company_code: record.company_code
            }
            DetailModalRef.current?.showModal(obj)
          }}>
          {text}
        </Button>
      )
    },
    {
      title: '相关企业',
      dataIndex: 'company_name',
      width: 300,
      render: (text: string, record: any) => (
        <Button type="link" onClick={() => openCompanyDetail(record.company_code, 'industryWarning')}>
          {text}
        </Button>
      )
    },
    {
      title: '事件分类',
      dataIndex: 'event_segment'
    },
    {
      title: '重要程度',
      dataIndex: 'event_grade'
    },
    {
      title: '来源',
      dataIndex: 'event_source'
    }
  ]
  const [data, setdata] = useState<any[]>([])
  const [pagination, setpagination] = useState({
    page: 1,
    page_size: PAGE_SIZE
  })
  const addPageFlag = useRef(false)
  const { AddTrackModal, doOpenTrack } = useAddTrack({
    success: () => {
      getLeftData()
    }
  })
  const { AddCompanyModal, doOpenCompany } = useAddCompany({
    success: () => {
      getLeftData()
    }
  })
  const { CompanyManageModal, doOpenCompanyManage } = useCompanyManage(selectedTrackItem)
  const { run } = useDebounceFn(
    (event: any) => {
      const { scrollTop, clientHeight, scrollHeight } = event.target
      if (scrollTop + clientHeight >= scrollHeight - 400 && !addPageFlag.current && hasMore) {
        setpagination({
          ...pagination,
          page: pagination.page + 1
        })
        addPageFlag.current = true
      }
    },
    {
      wait: 500
    }
  )
  const [hasMore, setHasMore] = useState(false)
  const [showCompanyTotal, setshowCompanyTotal] = useState(0)
  const [showEventTotal, setshowEventTotal] = useState(0)

  const resetPage = () => {
    setpagination({
      page: 1,
      page_size: PAGE_SIZE
    })
  }
  const resetRightSearch = () => {
    setrightHeaderTabIndex(0)
    setoccur_date__before(null)
    setshowCompanyTotal(0)
    setshowEventTotal(0)
    setevent_sub_type(null)
    setevent_segment(null)
    settableActiveKey('1')
    setkeywords(null)
    setevent_grade(null)
    resetPage()
    setdata([])
  }
  const handleShowArea = (item: { node_name?: any; node_id?: any; region: any; count?: number }) => {
    return item.region ? item.region.split('-').at(-1)?.split('|')[0] : !selectedTrackItem.showlistsmanage ? '全国' : ''
  }

  const getLeftData = () => {
    const p1 = getMonitorsTrackList({})
    const p2 = getMonitorsRollCallList({})
    Promise.allSettled([p1, p2])
      .then((res: any) => {
        const leftTabList = [
          {
            label: (
              <Flex align="center" gap={'small'}>
                <img className="w-14px" src="/static/img/Monitors/赛道监测.png" alt="" />
                <p>赛道监测</p>
              </Flex>
            ),
            key: '赛道监测',
            children: res[0].value.items
              .map((item: { node_name: any; id: any; region: string; count: number }) => ({
                ...item,
                label: (
                  <Flex align="center" gap={'small'} justify="space-between">
                    <div className="leading-16px">
                      {item.node_name}
                      <p className="leading-14px text-12px">{handleShowArea(item)}</p>
                    </div>
                    <p>{item.count}家</p>
                  </Flex>
                ),
                key: item.id
              }))
              .concat({
                label: (
                  <Button
                    type="primary"
                    shape="round"
                    className="w-full"
                    onClick={() => {
                      doOpenTrack()
                    }}>
                    管理赛道
                  </Button>
                ),
                key: '管理赛道'
              })
          },
          {
            label: (
              <Flex align="center" gap={'small'}>
                <img className="w-14px" src="/static/img/Monitors/企业名单监测.png" alt="" />
                <p>企业名单监测</p>
              </Flex>
            ),
            key: '企业名单监测',
            children: res[1].value.items
              .map((item: { name: any; id: any; count: number }) => ({
                ...item,
                label: (
                  <Flex align="center" gap={'small'} justify="space-between">
                    <div className="leading-16px">{item.name}</div>
                  </Flex>
                ),
                key: item.id,
                showlistsmanage: 'true'
              }))
              .concat({
                label: (
                  <Button
                    type="primary"
                    shape="round"
                    className="w-full"
                    onClick={() => {
                      doOpenCompany()
                    }}>
                    管理监测名单
                  </Button>
                ),
                key: '管理监测名单'
              })
          }
        ]
        setleftTabItems(leftTabList)
        setOpenKeys(leftTabList.map((item) => item.key))
        let selectedItem = leftTabList[0].children[0]
        if (searchParams.get('tab')) {
          const firstItem = leftTabList.find((first) => first.key === searchParams.get('tab'))
          if (searchParams.get('tab') === '赛道监测') {
            selectedItem = firstItem?.children.find(
              (second: { node_id: string; key: string }) => second.node_id === searchParams.get('node_id') && second.key === searchParams.get('key')
            )
          } else {
            // 企业名单监测
            selectedItem = firstItem?.children.find((second: { key: string }) => second.key === searchParams.get('node_id'))
          }
        }
        setselectedTrackItem(selectedItem || {})
        setselectedKeys([selectedItem?.key])
      })
      .finally(() => {
        setloading(false)
      })
  }
  const getEveryCompanyRelationEvents = (dataSource: any[]) => {
    dataSource.forEach(async (item: { company_code: any; page: any; page_size: any; total: any; dataSource: any; company_name: string }) => {
      setloading(true)
      getCompanyEventsList({
        monitor_track_id: !selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
        monitor_list_id: selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
        event_quality: rightHeaderTabIndex ? '利好' : '预警',
        company_code: item.company_code,
        page: item.page,
        page_size: item.page_size,
        event_sub_type,
        event_segment
      })
        .then((res) => {
          item.total = res.total
          item.dataSource = res.items
          item.company_name = res.items.length ? res.items[0].company_name : ''
          setdata([...dataSource])
        })
        .finally(() => {
          setloading(false)
        })
    })
  }

  useEffect(() => {
    setloading(true)
    getLeftData()
    if (searchParams.get('openTrack')) {
      doOpenTrack()
    }
  }, [])
  useEffect(() => {
    setloading(true)
    getLeftData()
    if (searchParams.get('openTrack')) {
      doOpenTrack()
    }
  }, [searchParams])

  useEffect(() => {
    if (selectedTrackItem.id) {
      setloading(true)
      // 监测预警详情
      const params = {
        monitor_track_id: !selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
        monitor_list_id: selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
        occur_date__before: occur_date__before || undefined,
        occur_date__after: occur_date__before ? dayjs().format('YYYY-MM-DD') : undefined
      }
      const p1 = getCompanyEventsStatistics({
        ...params,
        event_quality: '预警'
      })
      const p2 = getCompanyEventsStatistics({
        ...params,
        event_quality: '利好'
      })
      Promise.allSettled([p1, p2])
        .then((res: any[]) => {
          setfilterTabs(rightHeaderTabIndex ? res[1].value?.items : res[0].value?.items)
          setrightHeaderTabs([
            {
              label: '预警',
              value: res[0].value?.items?.reduce((total: number, current: any) => total + current.count, 0)
            },
            {
              label: '利好',
              value: res[1].value?.items?.reduce((total: number, current: any) => total + current.count, 0)
            }
          ])
        })
        .finally(() => {
          setloading(false)
        })
      setshowCompanyTotal(selectedTrackItem.count)
    }
  }, [selectedTrackItem, rightHeaderTabIndex, occur_date__before])

  useEffect(() => {
    if (selectedTrackItem.id) {
      if (tableActiveKey === '1') {
        setloading(true)
        // 汇总
        getCompanyEventsList({
          monitor_track_id: !selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
          monitor_list_id: selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
          keywords,
          occur_date__before: occur_date__before || undefined,
          occur_date__after: occur_date__before ? dayjs().format('YYYY-MM-DD') : undefined,
          event_quality: rightHeaderTabIndex ? '利好' : '预警',
          event_grade,
          event_sub_type,
          event_segment,
          ...pagination
        })
          .then((res) => {
            if (pagination.page === 1) {
              setdata(res.items ?? [])
            } else {
              setdata([...data, ...res.items])
            }
            addPageFlag.current = false
            if (res.total > pagination.page * pagination.page_size) {
              setHasMore(true)
            } else {
              setHasMore(false)
            }
            setshowEventTotal(res.total)
          })
          .finally(() => {
            setloading(false)
          })
      } else {
        setloading(true)
        // 按公司
        getCompanyEventsCompanyList({
          monitor_track_id: !selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
          monitor_list_id: selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
          keywords,
          occur_date__before: occur_date__before || undefined,
          occur_date__after: occur_date__before ? dayjs().format('YYYY-MM-DD') : undefined,
          event_quality: rightHeaderTabIndex ? '利好' : '预警',
          event_grade,
          event_sub_type,
          event_segment,
          ...pagination
        })
          .then((res) => {
            let dataSource = []
            if (pagination.page === 1) {
              dataSource = res.items.map((item: any) => ({
                ...item,
                page: 1,
                page_size: 10
              }))
            } else {
              dataSource = [
                ...data,
                ...res.items.map((item: any) => ({
                  ...item,
                  page: 1,
                  page_size: 10,
                  total: 0
                }))
              ]
            }
            setdata(dataSource)
            addPageFlag.current = false
            if (res.total > pagination.page * pagination.page_size) {
              setHasMore(true)
            } else {
              setHasMore(false)
            }
            getEveryCompanyRelationEvents(dataSource)
          })
          .finally(() => {
            setloading(false)
          })
      }
    }
  }, [selectedTrackItem, rightHeaderTabIndex, occur_date__before, pagination, event_grade, tableActiveKey])

  return (
    <div className="biomedical-area-page-wrapper">
      {loading && <HsAdminSpin />}
      <Flex gap="large">
        <Menu
          className="left-tabs"
          mode="inline"
          openKeys={OpenKeys}
          selectedKeys={selectedKeys}
          items={leftTabItems}
          onClick={({ key, keyPath }: { key: string; keyPath: string[] }) => {
            if (Object.is(key, selectedTrackItem.key)) {
              return
            }
            if (!['管理赛道', '管理监测名单'].includes(key)) {
              const firstItem = leftTabItems.find((first) => Object.is(first.key, keyPath.at(-1)))
              const selectedItem = firstItem.children?.find((item: { key: string | null }) => item.key === key)
              setselectedTrackItem(selectedItem || {})
              setselectedKeys([selectedItem?.key])
              resetRightSearch()
            }
          }}
          onOpenChange={(openKeys: string[]) => {
            setOpenKeys(openKeys)
          }}
        />
        <div className="right-box-wrapper">
          <Flex align="center" gap={'middle'} justify="space-between" className="my-2 h-43px">
            <Flex align="center" gap={'middle'}>
              <h1 className="module-title">{selectedTrackItem.node_name}</h1>
              <p className="text-#262626 text-12px line-height-12px">{handleShowArea(selectedTrackItem)}</p>
              <div className="right-header-tab">
                {rightHeaderTabs.map((item, index) => (
                  <div
                    className={classNames(['tab-item', rightHeaderTabIndex === index ? 'active' : ''])}
                    key={item.label}
                    onClick={() => {
                      resetRightSearch()
                      setrightHeaderTabIndex(index)
                    }}>
                    <p className="flex-none">{item.label}</p>
                    <b>{item.value}</b>
                  </div>
                ))}
              </div>
              <Flex align="center" gap={'small'} className="ml-4">
                <span>时间范围：</span>
                <HsAdminSelect
                  value={occur_date__before}
                  placeholder="请选择时间范围"
                  options={[
                    { label: '近7天', value: dayjs().subtract(7, 'day').format('YYYY-MM-DD') },
                    { label: '近一月', value: dayjs().subtract(1, 'month').format('YYYY-MM-DD') },
                    { label: '近三月', value: dayjs().subtract(3, 'month').format('YYYY-MM-DD') },
                    { label: '近一年', value: dayjs().subtract(1, 'year').format('YYYY-MM-DD') }
                  ]}
                  onChange={(value: SetStateAction<string | null>) => {
                    setoccur_date__before(value)
                  }}
                  className="w-60"
                />
              </Flex>
            </Flex>
            <Flex align="center" gap={'middle'}>
              <p>
                {showCompanyTotal} 家企业，共 {showEventTotal} 条动态
              </p>
              {selectedTrackItem.showlistsmanage && (
                <div
                  className="roll-call-btn"
                  onClick={() => {
                    doOpenCompanyManage()
                  }}>
                  <img src="/static/img/Monitors/名单管理.png" alt="" />
                  <p>企业管理</p>
                </div>
              )}
            </Flex>
          </Flex>
          {false && (
            <div className="chart-wrapper">
              <h1 className="module-title">预警监测指数变化情况</h1>
              <img src="/static/img/Monitors/empty.png" alt="" />
            </div>
          )}
          <div className="filter-wrapper">
            <Flex align="center" gap={'middle'} justify="space-between" className="filter-header mb-2">
              <Flex align="center" gap={'middle'}>
                <i></i>
                <h1 className="module-title">监测预警详情</h1>
              </Flex>
            </Flex>
            <Flex gap={'middle'}>
              {filterTabs?.map((first, index) => (
                <div className="column-box" key={index}>
                  <div
                    className={classNames([
                      'first-title',
                      first.disabled ? 'disabled' : '',
                      'cursor-pointer',
                      first.name === event_sub_type ? 'active' : ''
                    ])}
                    onClick={() => {
                      if (event_sub_type === first.name) {
                        setevent_sub_type(null)
                        setevent_segment(null)
                      } else {
                        setevent_sub_type(first.name)
                        setevent_segment(null)
                      }
                      resetPage()
                    }}>
                    {first.name}&nbsp;
                    {first.count}
                  </div>
                  <i className="divider"></i>
                  {first.children.map((second: any, sIdx: number) => (
                    <div
                      className={classNames([
                        'second-title',
                        second.disabled ? 'disabled' : '',
                        'cursor-pointer',
                        second.name === event_segment ? 'active' : ''
                      ])}
                      key={sIdx}
                      onClick={() => {
                        setevent_sub_type(first.name)
                        if (event_segment === second.name) {
                          setevent_segment(null)
                        } else {
                          setevent_segment(second.name)
                        }
                        resetPage()
                      }}>
                      {second.name}&nbsp;
                      {second.count}
                    </div>
                  ))}
                </div>
              ))}
            </Flex>
          </div>
          <div className="table-box">
            <Flex align="center" gap={'middle'} className="search-box">
              <HsAdminInput
                value={keywords}
                placeholder={tableActiveKey === '2' ? '输入企业名称' : '输入标题名称'}
                Search
                onChange={(e: { target: { value: SetStateAction<null> } }) => setkeywords(e.target.value)}
                onPressEnter={(e: { target: { value: SetStateAction<null> } }) => {
                  setkeywords(e.target.value)
                  resetPage()
                }}
                onSearch={(value: SetStateAction<null>) => {
                  setkeywords(value)
                  resetPage()
                }}
              />
              <Flex align="center" gap={'middle'}>
                <span className="flex-none">重要性：</span>
                <HsAdminSelect
                  value={event_grade}
                  placeholder="请选择重要性"
                  options={[
                    { label: '重要', value: '重要' },
                    { label: '一般', value: '一般' }
                  ]}
                  onChange={(value: SetStateAction<string | null>) => setevent_grade(value)}
                />
                <Button
                  type="link"
                  onClick={() => {
                    setkeywords(null)
                    setevent_grade(null)
                    resetPage()
                  }}>
                  重置
                </Button>
              </Flex>
            </Flex>
            <Tabs
              activeKey={tableActiveKey}
              items={[
                {
                  key: '1',
                  label: '汇总',
                  children: (
                    <>
                      <HsAdminTable
                        columns={columns}
                        dataSource={data}
                        id="monitors-main-collect-list"
                        size="small"
                        rowKey={(record) => JSON.stringify(record) + Math.random()}
                        scroll={{ y: 700 }}
                        pagination={false}
                        onScroll={run}
                      />
                    </>
                  )
                },
                {
                  key: '2',
                  label: '按公司',
                  children: (
                    <div id="scrollableDiv" className="h-175 overflow-auto">
                      <InfiniteScroll
                        dataLength={data.length} //This is important field to render the next data
                        next={() => {
                          setpagination({
                            ...pagination,
                            page: pagination.page + 1
                          })
                        }}
                        hasMore={hasMore}
                        loader={<HsAdminSpin />}
                        scrollableTarget="scrollableDiv">
                        {data.map((item, index) => (
                          <div key={index}>
                            <p>{item.company_name}</p>
                            <HsAdminTable
                              columns={columns}
                              dataSource={item.dataSource}
                              size="small"
                              rowKey={(record) => JSON.stringify(record) + Math.random()}
                              resizeable={false}
                              pagination={false}
                            />
                            <Flex justify="flex-end">
                              <HsAdminPage
                                current={item.page}
                                pageSize={item.page_size}
                                total={item.total}
                                showSizeChanger={false}
                                onChange={(page: any) => {
                                  item.page = page
                                  setdata([...data])
                                  setloading(true)
                                  getCompanyEventsList({
                                    monitor_track_id: !selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
                                    monitor_list_id: selectedTrackItem.showlistsmanage ? selectedTrackItem.id : undefined,
                                    event_quality: rightHeaderTabIndex ? '利好' : '预警',
                                    company_code: item.company_code,
                                    page: item.page,
                                    page_size: item.page_size,
                                    event_sub_type,
                                    event_segment
                                  })
                                    .then((res) => {
                                      item.total = res.total
                                      item.dataSource = res.items
                                      setdata([...data])
                                    })
                                    .finally(() => {
                                      setloading(false)
                                    })
                                }}
                              />
                            </Flex>
                          </div>
                        ))}
                      </InfiniteScroll>
                    </div>
                  )
                }
              ]}
              onChange={(activeKey) => {
                if (activeKey === '2') {
                  PAGE_SIZE = 10
                } else {
                  PAGE_SIZE = 30
                }
                resetPage()
                settableActiveKey(activeKey)
              }}
            />
          </div>
        </div>
      </Flex>
      {AddTrackModal}
      {AddCompanyModal}
      {CompanyManageModal}
      <DetailModal ref={DetailModalRef} />
    </div>
  )
}

export default Monitors
